package me.luger.core.mvc.controller;

import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;

/**
 * Created by luger on 2016/12/4 0004.
 */
//@Component
public class MultiViewResover implements ViewResolver {

    private static Map<String, ViewResolver> resolvers ;

    /**
     * 默认视图类型为jsp视图
     */
    private static final String DEFAULT_VIEW_TYPE = "jsp";

    @Override
    public View resolveViewName(String viewName, Locale locale) throws Exception {
        int n = viewName.lastIndexOf(":"); // 获取
        String suffix = MultiViewResover.DEFAULT_VIEW_TYPE;
        // 默认使用jsp视图
        if (n != -1) {
            // 有的话截取:前面的字符串 这里一般是jsp,ftl,vm,th与Map resolvers中的key匹配
            suffix = viewName.substring(0, n);
            // 取:后面的部分 那时真正的资源名.比如我们要使用hello.jsp 那viewName就应该是jsp:hello
            viewName = viewName.substring(n+1);
        }
        // 根据:前面的字符串去获取托管的视图解析类对象
        ViewResolver resolver = resolvers.get(suffix);

        if (resolver != null)
            return resolver.resolveViewName(viewName, locale);
        return null;
    }

    public Map<String, ViewResolver> getResolvers() {
        return resolvers;
    }

    public void setResolvers(Map<String, ViewResolver> resolvers) {
        this.resolvers = resolvers;
    }

}


